<template>
  <view>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <!-- <customHeader v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></customHeader> -->
    <view class="applyInvoice">
      <!-- <h2 class="invoice-title font_syHeavy">申请发票</h2> -->
      <toptitle title="申请发票" :textArr="['尊贵的麦卡伦贵宾，请填写您的发票信息']"/>
      <view class="invoice-content">
        <view class="flex_space_between height_74">
          <view class="text_24">订单编号</view>
          <view class="text_24 color_75">{{ orderDetail.orderCode }}</view>
        </view>
        <view class="flex_space_between height_74" v-if="invoiceAmount > 0">
          <view class="text_24">开票金额</view>
          <view class="text_24 color_75">{{ '￥' + filterChecked.moneyFormat(invoiceAmount, 2)}}</view>
        </view>
        <view class="line_style"></view>
        <view class="invo-orderCode flex_space_between">
          <view class="NotoSansSC_Medium">发票类型</view>
          <view class="text_24 color_75">增值税电子普通发票</view>
        </view>
        <view class="invo-orderCode">
          <view class="invoice_title">抬头类型 <text class="bitian">(必填)</text> </view>
          <view class="businessType">
            <view class="col-l" v-for="(item, index) in businessTypeArr" :key="index" @click="businessTypeHandle"
              :data-index="index" :data-type="item">
                <image class="label-1__icon" :data-index="index" :data-orderItemId="item.orderItemId" :data-refundFee="item.price"
                  :src="businessTypeIndex === index ? selIconImg : noSelIconImg"></image>
              {{ item }}
            </view>
          </view>
        </view>
        <view class="invo-orderCode">
          <text class="invoice_title">发票抬头<text class="bitian">(必填)</text></text>
          <text class="choose" @click="choosePayerRegisterNo">选择我的抬头</text>
          <input class="input" @input="bindpayerName" :value="payerName" :placeholder="businessType == 2 ?'请输入公司名称':'填写“个人”或抬头名称'" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode" v-if="businessType == 2">
          <view class="invoice_title">税号<text class="bitian">(必填)</text></view>
          <input class="input" @input="bindtaxNumber" :value="payerRegisterNo" placeholder="请输入纳税人识别号" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode">
          <text class="invoice_title">邮箱地址<text class="bitian">(必填)</text></text>
          <input class="input" :value="payerEmail" @input="bindEmail" placeholder="成功开票后,发票将发送至此邮箱" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode" v-if="businessType == 2 || businessTypeIndex == -1">
          <text class="invoice_title">开户银行<text class="bitian">(选填)</text></text>
          <input class="input" :value="payerBank" @input="handleInput" data-name="payerBank" placeholder="请输入开户银行" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode" v-if="businessType == 2 || businessTypeIndex == -1">
          <text class="invoice_title">银行账号<text class="bitian">(选填)</text></text>
          <input class="input" :value="payerAccount" @input="handleInput" data-name="payerAccount" placeholder="请输入银行账号" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode" v-if="businessType == 2 || businessTypeIndex == -1">
          <text class="invoice_title">企业地址<text class="bitian">(选填)</text></text>
          <input class="input" :value="payerAddress" @input="handleInput" data-name="payerAddress" placeholder="请输入企业地址" placeholder-class="color_c6"/>
        </view>
        <view class="invo-orderCode" v-if="businessType == 2 || businessTypeIndex == -1">
          <text class="invoice_title">企业电话<text class="bitian">(选填)</text></text>
          <input class="input" :value="payerPhone" @input="handleInput" data-name="payerPhone" placeholder="请输入企业电话" placeholder-class="color_c6" />
        </view>
        <view class="btn_box">
          <view class="btn_tips">*电子发票将于确认收货后开出，具体进度可查看发票或联系在线客服</view>
          <view class="button" @click="handleRefer" :class="canSubmit ? 'button_active' : ''">提交申请</view>
        </view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import customize from '@/utils/customize';
  import Loading from '@/components/common/loading';
  import customHeader from '@/components/common/custom';
  import NavBar from '@/components/common/navbar';
  import toptitle from './components/toptitle';
  import {
    SYSTEM_INFO,
    CUSTOMER_INFO,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  export default {
    components: {
      customHeader: customHeader,
      navBar: NavBar,
      toptitle: toptitle
    },
    data() {
      return {
        // navbarData: {
        //   flag: 1, //
        //   name: '' //导航栏 中间的标题
        // },
        // isShowCustomNavBar: true,
        isShowCustomNavBar: true,
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '发票信息', //导航栏 中间的标题
          hideSearch: true,
          hideHome: true
        },
        orderNo: '',
        businessTypeArr: ['个人/事业单位', '企业'],
        businessTypeIndex: -1,
        businessType: '',
        payerName: '',      //  发票抬头
        payerRegisterNo: '', // 发票税号
        payerAccount: "",  //  银行账号（选填）
        payerAddress: "",  //  企业地址（选填）
        payerBank: "",     //  开户银行（选填）
        payerPhone: "",    //  企业电话（选填）
        invoiceAmount: 0,  //  开票金额
        payerEmail: '',    //  邮箱地址
        orderDetail: {},
        flag: false,
        nowPages: '',
        btnActive: true,
        selIconImg: "",
        noSelIconImg: "",
        canSubmit: false
      };
    },

    onLoad(option) {
      let that = this;
      that.orderNo = option.orderNo;
      that.getOrderInfo();
      that.wosaiInvoiceAmount();
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
      const { unselectedCheckboxSvgImg,selectedCheckboxSvgImg } = require('./components/imgs.svg.js');
      this.selIconImg = selectedCheckboxSvgImg(this.imgColor);
      this.noSelIconImg = unselectedCheckboxSvgImg(this.imgColor);
    },

    onShow() {
      let that = this
      if (that.flag) {
        uni.navigateBack();
      }
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '申请发票',
      })
    },

    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      // 根据订单号查询详情
      getOrderInfo: async function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const json = await api.getOrderInfo({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );
        if (json.code === 1000) {
          this.orderDetail = json.data;
        }
      },

      // 计算开发票金额
      wosaiInvoiceAmount: async function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const amount = await api.getwosaiInvoiceAmount({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );
        if (amount.code === 1000) {
          that.invoiceAmount = amount.data.invoiceAmount;
        }
      },
      /**
       * 开蓝票
       * @param {Object} params 1个人/事业单位  2企业
       */
      wosaiInvoiceBlue: async function(params) {
        let that = this;
				uni.showLoading({title: '加载中'});
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const invoiceList = await api.getwosaiInvoiceBlue({
            method: 'POST',
            header: {
              jwt: customerInfo.jwt
            },
            query: params
          },
          this.orderNo
        );
				uni.hideLoading();
        if (invoiceList.code == 1000) {
          this.btnActive = true;
          let invoiceItems = invoiceList.data;
          let taskSn = invoiceItems.taskSn;
					
          this.handleShowTextToast('申请成功');
          that.flag = true;
          this.payerRegisterNo = '';
          that.payerAccount = '';  //  银行账号（选填）
          that.payerAddress = "";  //  企业地址（选填）
          that.payerBank = "";     //  开户银行（选填）
          that.payerPhone = "";    //  企业电话（选填）
          uni.navigateTo({
            url: '/pages/invoice/details?tasksn=' + taskSn + '&orderNo=' + this.orderNo
          });
        } else if (invoiceList.code == -1010) {
          this.btnActive = true;
          this.handleShowTextToast('开票异常，请联系客服处理');
          that.flag = false;
        } else {
          this.btnActive = true
          that.flag = false
          if (invoiceList.code == -1006) {
            this.handleShowTextToast('已申请发票，请勿重复开票');
          } else {
            this.handleShowTextToast(invoiceList.msg);
          }
          setTimeout(() => {
            uni.navigateBack();
          }, 2500);
        }
      },

      // 选择抬头类型
      businessTypeHandle(e) {
        let index = e.currentTarget.dataset.index;
        let type = e.currentTarget.dataset.type;
        this.businessTypeIndex = index;
        this.businessType = index + 1;
      },

      // 选择我的抬头
      choosePayerRegisterNo() {
        let that = this;
        wx.chooseInvoiceTitle({
          success(res) {
            // 0 单位 1个人
            that.payerName = res.title;
            if (that.businessType == 2) {
              that.payerRegisterNo = res.taxNumber || '';
              that.payerAccount = res.bankAccount || '';  //  银行账号（选填）
              that.payerAddress = res.companyAddress || "";  //  企业地址（选填）
              that.payerBank = res.bankName || "";     //  开户银行（选填）
              that.payerPhone = res.telephone || "";    //  企业电话（选填）
            }
          }
        });
      },
      // 填写发票抬头
      bindpayerName(e) {
        this.payerName = e.detail.value;
        this.submitBtn();
      },
      // 填写税号
      bindtaxNumber(e) {
        this.payerRegisterNo = e.detail.value;
        this.submitBtn();
      },
      // 填写邮箱
      bindEmail(e) {
        this.payerEmail = e.detail.value;
        this.submitBtn();
      },
      submitBtn(){
        if(this.businessType == 2){
          this.canSubmit = this.payerName && this.payerRegisterNo && this.payerEmail ? true : false;
        }else{
          this.canSubmit = this.payerName && this.payerEmail ? true : false;
        }
      },
      // 其他信息
      handleInput(e){
        const {currentTarget:{dataset:{name}},detail:{value}} = e;
        if(name) this[name] = value;
      },
      // 提交申请
      handleRefer() {
        if (!this.btnActive) return;
        let that = this;
        var emil = that.payerEmail;
        var myregs = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
        const regex = /^(((1[35789][0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
        const taxNumberRegs = /^([0-9a-zA-Z]{12,20})$/
        const space = /^\s*$/
        if (that.businessType == '' || that.businessType == null || that.businessType == undefined) {
          that.handleShowTextToast('请补充必填信息');
          return;
        }

        if (that.payerName == '' || that.payerName == null || that.payerName == undefined) {
          that.handleShowTextToast('请补充必填信息');
          return;
        }
        if (that.businessType == 2) {
          if (!that.payerRegisterNo) {
            that.handleShowTextToast('请补充必填信息');
            return
          }
          if (!(taxNumberRegs.test(that.payerRegisterNo)) && !space.test(that.payerRegisterNo)) {
            that.handleShowTextToast('税号格式有误，请重新输入')
            return
          }
        }

        if (that.payerEmail == '' || that.payerEmail == null || that.payerEmail == undefined) {
          that.handleShowTextToast('请补充必填信息');
          return;
        }
        if (!(myregs.test(emil))) {
          that.handleShowTextToast('邮箱格式不正确');
          return;
        }
        let obj = {
          businessType: that.businessType,
          payerEmail: that.payerEmail,
          payerName: that.payerName,
        }

        if (that.businessType == 2) {
          obj.payerRegisterNo = that.payerRegisterNo;
          if(that.payerAccount){
						const numberRegs = /^([0-9a-zA-Z]{12,24})$/
            if (!(numberRegs.test(that.payerAccount)) && !space.test(that.payerAccount)) {
              return that.handleShowTextToast('银行账号有误，请重新输入');
            }
            obj.payerAccount = that.payerAccount;
          }
          if(that.payerAddress) obj.payerAddress = that.payerAddress;
          if(that.payerBank) obj.payerBank = that.payerBank;
          if(that.payerPhone) obj.payerPhone = that.payerPhone;
          this.btnActive = false;
          that.wosaiInvoiceBlue(obj);
        } else if (that.businessType == 1) {
          this.btnActive = false;
          that.wosaiInvoiceBlue(obj);
        }
      }
    }
  };
</script>

<style lang="less">
  .applyInvoice {
    font-size: 28rpx;
    margin-bottom: 200rpx;
  }
  view,
  text, input {
    font-size: 28rpx;
    font-family: FrankNew-Regular,NotoSansSC-Regular;
  }
  .invoice-title {
    font-size: 40rpx;
    text-align: center;
    padding: 50rpx 0;
    border-bottom: 1px solid #8c8c8c;
  }
  .invoice-content {
    padding: 0 48rpx;
    margin-top: 32rpx;
    .invo-orderCode {
      margin-bottom: 32rpx;
      .businessType {
        display: flex;
        justify-content: space-between;
        margin-top: 16rpx;
        padding-bottom: 32rpx;
        border-bottom: 1px solid #f2f2f2;
      }
      .label-1__icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 20rpx;
        position: relative;
      }

      .col-l {
        display: flex;
        padding-right: 80rpx;
        align-items: center;
        justify-content: center;
        height: 48rpx;
        line-height: 48rpx;
      }
      .choose {
        border-bottom: 1px solid #000;
        padding-bottom: 4px;
        float: right;
      }
      .input {
        padding: 24rpx 0 10rpx;
        border-bottom: 1px solid #f2f2f2;
        height: 48rpx;
        font-family: FrankNew-Regular,NotoSansSC-Regular;
      }
    }

    .btn_box{
      padding-top: 120rpx;
      padding-bottom: 40px;
      text-align: center;
    }
    .btn_tips{
      font-size: 20rpx;
      font-weight: normal;
      color: #757575;
      margin-bottom: 20rpx;
    }
    .button {
      width: 100%;
      text-align: center;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 48rpx 16rpx 48rpx 48rpx;
      box-sizing: content-box;
      background-color: #C6C6C6;
      color: #757575;
    }

    .button_active{
      background-color: #000 !important;
      color: #fff !important;
    }
    .bitian {
      color: #C6C6C6;
      margin-left: 20rpx;
    }

    .text_24{
      font-size: 24rpx;
      font-weight: normal;
    }
    .color_75{
      color: #757575;
    }
    .height_74{
      height: 74rpx;
      line-height: 74rpx;
    }
    .line_style{
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
      margin: 32rpx 0;
    }
    .invoice_title{
      width: 100%;
      height: 48rpx;
      line-height: 48rpx;
      font-size: 28rpx;
      font-weight: normal;
      // font-family: NotoSansSC-Regular;
    }
    .color_c6{
      color: #C6C6C6 !important;
    }
  }
  .flex_space_between{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .NotoSansSC_Medium{
    font-family: NotoSansSC-Medium;
  }
</style>
